﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Common.Entity;
using ESOL.Business.Mst;
using ESOL.Business.Prod;
using ESOL.Business.Sales;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid;
using ESOL.Business.Proj;
using DevExpress.XtraEditors.Repository;
using ESOL.WinUI.MasterData;
using ESOL.Common;

namespace ESOL.WinUI.Manufacture
{
    public partial class frmMaintainManufactureTechnic : BaseForm.frmBaseDialogyMaintainForm
    {
        #region vars
        private DataSet Ds;
        private ProdPlanOrderItemEntity mSelectedProdPlanOrderItem;
        private bool bIsModify = false;
        private List<DataRow> listDeleteItem = new List<DataRow>();
        private List<DataRow> listDeleteItemDetail = new List<DataRow>();
        #endregion

        #region ctors
        public frmMaintainManufactureTechnic(ProdPlanOrderItemEntity entity)
        {
            InitializeComponent();
            mSelectedProdPlanOrderItem = entity;
        }
        #endregion

        #region functions
        private void Init()
        {
            Ds = new DataSet();
            DataTable DtProdProductTechnic = new DataTable();
            DtProdProductTechnic.TableName = "PROD_PRODUCT_TECHNIC";
            DataTable DtProdProductTechnicItem = new DataTable();
            DtProdProductTechnicItem.TableName = "PROD_PRODUCT_TECHNIC_ITEM";
            DtProdProductTechnic.Columns.Add("PRODUCT_TECHNIC_ID", typeof(string));
            DtProdProductTechnic.Columns.Add("PLAN_ORDER_ITEM_ID", typeof(string));
            DtProdProductTechnic.Columns.Add("TECHNIC_ID", typeof(string));
            DtProdProductTechnic.Columns.Add("TECHNIC_NAME", typeof(string));
            DtProdProductTechnic.Columns.Add("TECHNIC_CODE", typeof(string));
            DtProdProductTechnic.Columns.Add("TECHNIC_TYPE", typeof(string));
            DtProdProductTechnic.Columns.Add("GROUP_ID", typeof(string));
            DtProdProductTechnic.Columns.Add("GROUP_NAME", typeof(string));
            DtProdProductTechnic.Columns.Add("SEQUENCE", typeof(int));
            DtProdProductTechnic.Columns.Add("QTY", typeof(decimal));
            DtProdProductTechnic.Columns.Add("PRICE", typeof(decimal));
            DtProdProductTechnic.Columns.Add("GROUP_PERSON", typeof(string));
            DtProdProductTechnic.Columns.Add("PLAN_WORKING_HOURS", typeof(decimal));
            DtProdProductTechnic.Columns.Add("REMARK", typeof(string));
            DtProdProductTechnic.Columns.Add("COST", typeof(decimal));
            DtProdProductTechnic.Columns.Add("COEFFICIENT", typeof(decimal));
            DtProdProductTechnic.Columns.Add("PUR_APPLICATION_ITEM_ID", typeof(string));
            DtProdProductTechnic.Columns.Add("DELIVERY_DATE", typeof(DateTime));
            DtProdProductTechnic.Columns.Add("PLAN_STARTTIME", typeof(DateTime));

            DtProdProductTechnicItem.Columns.Add("PRODUCT_TECHNIC_ITEM_ID", typeof(string));
            DtProdProductTechnicItem.Columns.Add("PRODUCT_TECHNIC_ID", typeof(string));
            DtProdProductTechnicItem.Columns.Add("GROUP_PERSON", typeof(string));
            DtProdProductTechnicItem.Columns.Add("GROUP_PERSON_NAME", typeof(string));
            DtProdProductTechnicItem.Columns.Add("QTY", typeof(decimal));
            DtProdProductTechnicItem.Columns.Add("PLAN_STARTTIME", typeof(DateTime));
            DtProdProductTechnicItem.Columns.Add("PLAN_ENDTIME", typeof(DateTime));
            DtProdProductTechnicItem.Columns.Add("WORKING_TIME", typeof(decimal));
            DtProdProductTechnicItem.Columns.Add("TIME_COEFFICIENT", typeof(decimal));
            DtProdProductTechnicItem.Columns.Add("WORKCENTER_CODE", typeof(string));
            DtProdProductTechnicItem.Columns.Add("WORKCENTER_NAME", typeof(string));

            Ds.Tables.Add(DtProdProductTechnic);
            Ds.Tables.Add(DtProdProductTechnicItem);

            DataColumn KeyColumn = Ds.Tables["PROD_PRODUCT_TECHNIC"].Columns["PRODUCT_TECHNIC_ID"];         //主键
            DataColumn ForeignColumn = Ds.Tables["PROD_PRODUCT_TECHNIC_ITEM"].Columns["PRODUCT_TECHNIC_ID"];    //外键
            Ds.Relations.Add("明细", KeyColumn, ForeignColumn);     //从表的层次名

        }

        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(repositoryItemGridLookUpEdit1, "STT", false);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(repositoryItemGridLookUpEdit2, "STT", false);
        }

        private void SetField()
        {
            if (mSelectedProdPlanOrderItem == null)
                return;
            txtWorkingOrderCode.Text = mSelectedProdPlanOrderItem.OrderItemCode;
            txtPlanQty.Text = mSelectedProdPlanOrderItem.Qty.ToString();
            if (mSelectedProdPlanOrderItem.DeliveryDate != null)
            {
                dtpPlanDeliveryDate.EditValue = mSelectedProdPlanOrderItem.DeliveryDate;
            }
            ProdPlanOrderEntity mPlanOrder = ProdPlanOrderBs.GetProdPlanOrderByID(mSelectedProdPlanOrderItem.PlanOrderId);
            if (mPlanOrder != null)
            {
                SalesProdPlanApplicationItemEntity mApplicationItem = SalesProdPlanApplicationItemBs.GetProdPlanApplicationItemByID(mPlanOrder.ApplicationItemId);
                if (mApplicationItem != null)
                {
                    txtContractModel.Text = mApplicationItem.ProductSpecOut;
                }
            }
            MstProductEntity mProduct = MstProductBs.GetMstProductTypeByID(mSelectedProdPlanOrderItem.ProductId);
            if (mProduct == null)
                return;
            txtProductCode.Text = mProduct.ProductCode;
            txtProductName.Text = mProduct.ProductName;

        }

        private void LoadSourceStation()
        {
            string sCondition = " AND A.DELETE_FLAG='" + 0 + "' ";
            DataTable dt = ProdTechnicBs.GetProdTechnicByCondition("", sCondition, "");
            gvStations.DataSource = dt;
        }

        private void LoadTargetStation()
        {
            if (mSelectedProdPlanOrderItem == null)
                return;
            //如ProdProductTechnic存在记录，则绑定已保存数据
            DataTable dtProdProductTechnic = ProdProductTechnicBs.GetDtProdFlowByCondition(" and PPT.PLAN_ORDER_ITEM_ID='" + mSelectedProdPlanOrderItem.PlanOrderItemId + "'", " PPT.SEQUENCE ");
            if (dtProdProductTechnic != null && dtProdProductTechnic.Rows.Count > 0)
            {
                bIsModify = true;
                BindSavedProductTechnic(dtProdProductTechnic);
                return;
            }
            //如存在历史工艺，则绑定历史工艺
            DataTable dtHistoryTechnic = ProdHistoryTechnicBs.GetDtAllByProductID(mSelectedProdPlanOrderItem.ProductId);
            if (dtHistoryTechnic.Rows.Count > 0)
            {
                BindHistoryTechnic(dtHistoryTechnic);
                return;
            }
            //如存在BOM工艺，则绑定BOM工艺
            DataTable dtBomTechnic = ProjMBOMTechnicBs.GetDtAllByProductID(mSelectedProdPlanOrderItem.ProductId);
            if (dtBomTechnic.Rows.Count > 0)
            {
                BindBomTechnic(dtBomTechnic);
                return;
            }
            gvTargetStations.DataSource = Ds.Tables[0];
        }

        private void BindSavedProductTechnic(DataTable Dt)
        {
            DataTable dtMain = Ds.Tables["PROD_PRODUCT_TECHNIC"];
            foreach (DataRow dr in Dt.Rows)
            {
                DataRow drMain = dtMain.NewRow();
                drMain["PRODUCT_TECHNIC_ID"] = dr["PRODUCT_TECHNIC_ID"];
                drMain["PLAN_ORDER_ITEM_ID"] = dr["PLAN_ORDER_ITEM_ID"];
                drMain["TECHNIC_ID"] = dr["TECHNIC_ID"];
                drMain["TECHNIC_NAME"] = dr["TECHNIC_NAME"];
                drMain["TECHNIC_CODE"] = dr["TECHNIC_CODE"];
                drMain["TECHNIC_TYPE"] = dr["ITEM_NAME"];
                drMain["GROUP_ID"] = dr["GROUP_ID"];
                drMain["GROUP_NAME"] = dr["GROUP_NAME"];
                drMain["SEQUENCE"] = dr["SEQUENCE"];
                drMain["QTY"] = dr["QTY"];
                drMain["PRICE"] = dr["PRICE"];
                drMain["GROUP_PERSON"] = dr["GROUP_PERSON"];
                drMain["PLAN_WORKING_HOURS"] = dr["PLAN_WORKING_HOURS"];
                drMain["REMARK"] = dr["REMARK"];
                drMain["COST"] = dr["COST"];
                drMain["COEFFICIENT"] = dr["COEFFICIENT"];
                drMain["PUR_APPLICATION_ITEM_ID"] = dr["PUR_APPLICATION_ITEM_ID"];
                drMain["PLAN_STARTTIME"] = dr["PLAN_STARTTIME"];
                drMain["DELIVERY_DATE"] = dr["DELIVERY_DATE"];
                dtMain.Rows.Add(drMain);

                DataTable dtDetail = ProdProductTechnicItemBs.GetDtEntityByProductTechnicID(dr["PRODUCT_TECHNIC_ID"].ToString());
                if (dtDetail != null && dtDetail.Rows.Count > 0)
                {
                    foreach (DataRow drDetail in dtDetail.Rows)
                    {
                        Ds.Tables["PROD_PRODUCT_TECHNIC_ITEM"].ImportRow(drDetail);
                    }
                }
            }
            gvTargetStations.DataSource = dtMain;
            dtMain.AcceptChanges();
        }

        private void BindHistoryTechnic(DataTable Dt)
        {
            DataTable dtHistoryItem = ProdHistoryTechnicItemBs.GetDtAllByHistoryTechnicID(Dt.Rows[0]["ID"].ToString());
            DataTable dtMain = Ds.Tables["PROD_PRODUCT_TECHNIC"];
            foreach (DataRow dr in dtHistoryItem.Rows)
            {
                DataRow drMain = dtMain.NewRow();
                drMain["PRODUCT_TECHNIC_ID"] = Guid.NewGuid().ToString();
                drMain["PLAN_ORDER_ITEM_ID"] = mSelectedProdPlanOrderItem.PlanOrderItemId;
                drMain["TECHNIC_ID"] = dr["TECHNIC_ID"];
                drMain["TECHNIC_NAME"] = dr["TECHNIC_NAME"];
                drMain["TECHNIC_CODE"] = dr["TECHNIC_CODE"];
                drMain["TECHNIC_TYPE"] = dr["ITEM_NAME"];
                drMain["GROUP_ID"] = dr["GROUP_ID"];
                drMain["GROUP_NAME"] = dr["GROUP_NAME"];
                drMain["PLAN_WORKING_HOURS"] = dr["PLAN_WORKING_HOURS"];
                dtMain.Rows.Add(drMain);

                DataTable dtHistoryTechnicItemDetail = ProdHistoryTechnicItemDetailBs.GetDtAllByHistoryTechnicItemID(dr["ID"].ToString());
                foreach (DataRow dr2 in dtHistoryTechnicItemDetail.Rows)
                {
                    DataRow dr3 = Ds.Tables["PROD_PRODUCT_TECHNIC_ITEM"].NewRow();
                    dr3["PRODUCT_TECHNIC_ITEM_ID"] = Guid.NewGuid().ToString();
                    dr3["PRODUCT_TECHNIC_ID"] = drMain["PRODUCT_TECHNIC_ID"];
                    dr3["GROUP_PERSON"] = dr2["GROUP_PERSON"];
                    dr3["GROUP_PERSON_NAME"] = dr2["NAME_CN"];
                    dr3["WORKING_TIME"] = dr2["WORKING_TIME"];
                    Ds.Tables["PROD_PRODUCT_TECHNIC_ITEM"].Rows.Add(dr3);
                }
            }
            gvTargetStations.DataSource = Ds.Tables[0];
        }

        private void BindBomTechnic(DataTable Dt)
        {
            DataTable dtMain = Ds.Tables["PROD_PRODUCT_TECHNIC"];
            foreach (DataRow dr in Dt.Rows)
            {
                DataRow drMain = dtMain.NewRow();
                drMain["PRODUCT_TECHNIC_ID"] = Guid.NewGuid().ToString();
                drMain["PLAN_ORDER_ITEM_ID"] = mSelectedProdPlanOrderItem.PlanOrderItemId;
                drMain["TECHNIC_ID"] = dr["TECHNIC_ID"];
                drMain["TECHNIC_NAME"] = dr["TECHNIC_NAME"];
                drMain["TECHNIC_CODE"] = dr["TECHNIC_CODE"];
                drMain["TECHNIC_TYPE"] = dr["ITEM_NAME"];
                drMain["GROUP_ID"] = dr["GROUP_ID"];
                drMain["GROUP_NAME"] = dr["GROUP_NAME"];
                drMain["PLAN_WORKING_HOURS"] = dr["STD_WORKING_TIME"];
                dtMain.Rows.Add(drMain);
            }
            gvTargetStations.DataSource = dtMain;
        }

        #endregion

        #region events
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            Init();
            BindComboBox();
            SetField();
            LoadSourceStation();
            LoadTargetStation();
        }

        private GridHitInfo downHitInfo;
        private void gridView2_MouseDown(object sender, MouseEventArgs e)
        {
            downHitInfo = gridView2.CalcHitInfo(new Point(e.X, e.Y));
        }
        private void gridView2_MouseMove(object sender, MouseEventArgs e)
        {
            if (downHitInfo == null) return;
            if (e.Button != MouseButtons.Left) return;
            Rectangle dragRect = new Rectangle(new Point(
                downHitInfo.HitPoint.X - SystemInformation.DragSize.Width / 2,
                downHitInfo.HitPoint.Y - SystemInformation.DragSize.Height / 2), SystemInformation.DragSize);
            if (!dragRect.Contains(new Point(e.X, e.Y)))
            {
                DataRow data = gridView2.GetDataRow(downHitInfo.RowHandle);
                int[] rows = gridView2.GetSelectedRows();
                List<DataRow> row = new List<DataRow>();
                for (int i = 0; i < rows.Length; i++)
                    row.Add(gridView2.GetDataRow((int)rows[i]));
                gvStations.DoDragDrop(row, DragDropEffects.Copy);
            }
        }
        private void gvTargetStations_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }
        private void gvTargetStations_DragDrop(object sender, DragEventArgs e)
        {
            GridControl grid = sender as GridControl;
            DataTable table = grid.DataSource as DataTable;
            List<DataRow> row = e.Data.GetData(typeof(List<DataRow>)) as List<DataRow>;
            if (row != null && table != null)
            {
                if (row.Count > 0)
                {
                    DataTable dtTarget = (DataTable)gvTargetStations.DataSource;
                    for (int i = 0; i < row.Count; i++)
                    {
                        DataRow drSelectedSource = row[i];
                        DataRow drTarget = dtTarget.NewRow();
                        drTarget["PRODUCT_TECHNIC_ID"] = Guid.NewGuid().ToString();
                        drTarget["PLAN_ORDER_ITEM_ID"] = mSelectedProdPlanOrderItem.PlanOrderItemId;
                        drTarget["TECHNIC_ID"] = drSelectedSource["TECHNIC_ID"];
                        drTarget["TECHNIC_NAME"] = drSelectedSource["TECHNIC_NAME"];
                        drTarget["TECHNIC_CODE"] = drSelectedSource["TECHNIC_CODE"];
                        MstCommonItemEntity m = MstCommonItemBs.GetMstCommonItemByCode(drSelectedSource["STATION_TYPE"].ToString());
                        if (m != null)
                        {
                            drTarget["TECHNIC_TYPE"] = m.ItemName;
                        }
                        drTarget["GROUP_ID"] = drSelectedSource["GROUP_ID"];
                        MstWorkingGroupEntity mWorkingGroup = MstWorkingGroupBs.GetMstWorkingGroupByID(drSelectedSource["GROUP_ID"].ToString());
                        if (mWorkingGroup != null)
                        {
                            drTarget["GROUP_NAME"] = mWorkingGroup.GroupName;
                        }
                        drTarget["QTY"] = mSelectedProdPlanOrderItem.Qty;
                        string sCondition = " and TECHNIC_ID='" + drSelectedSource["TECHNIC_ID"].ToString() + "' and VALIDITY_FLAG=1";
                        sCondition += " and VALIDITY_DATE_FROM<='" + DateTime.Now.ToString("yyyy-MM-dd") + "'";
                        sCondition += " and VALIDITY_DATE_TO>='" + DateTime.Now.ToString("yyyy-MM-dd") + "'";
                        DataTable dtCost = ProdTechnicCostBs.GetDtAllByCondition(sCondition);
                        if (dtCost.Rows.Count != 0)
                        {
                            drTarget["COST"] = dtCost.Rows[0]["COST"];
                        }

                        sCondition = " and TECHNIC_ID='" + drSelectedSource["TECHNIC_ID"].ToString() + "' and VALIDITY_FLAG=1";
                        sCondition += " and QTY_FROM<='" + mSelectedProdPlanOrderItem.Qty.ToString() + "'";
                        sCondition += " and QTY_TO>='" + mSelectedProdPlanOrderItem.Qty.ToString() + "'";
                        DataTable dtRatio = ProdTechnicRatioBs.GetDtAllByCondition(sCondition);
                        if (dtRatio.Rows.Count != 0)
                        {
                            drTarget["COEFFICIENT"] = dtRatio.Rows[0]["RATIO"];
                        }
                        dtTarget.Rows.Add(drTarget);

                    }
                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            int[] arrySelectedIndex = gridView2.GetSelectedRows();
            if (arrySelectedIndex.Length == 0)
            {
                MessageBox.Show("请选择工序！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DataTable dtTarget = (DataTable)gvTargetStations.DataSource;
            for (int i = 0; i < arrySelectedIndex.Length; i++)
            {
                DataRow drSelectedSource = gridView2.GetDataRow(arrySelectedIndex[i]);
                DataRow drTarget = dtTarget.NewRow();
                drTarget["PRODUCT_TECHNIC_ID"] = Guid.NewGuid().ToString();
                drTarget["PLAN_ORDER_ITEM_ID"] = mSelectedProdPlanOrderItem.PlanOrderItemId;
                drTarget["TECHNIC_ID"] = drSelectedSource["TECHNIC_ID"];
                drTarget["TECHNIC_NAME"] = drSelectedSource["TECHNIC_NAME"];
                drTarget["TECHNIC_CODE"] = drSelectedSource["TECHNIC_CODE"];
                MstCommonItemEntity m = MstCommonItemBs.GetMstCommonItemByCode(drSelectedSource["STATION_TYPE"].ToString());
                if (m != null)
                {
                    drTarget["TECHNIC_TYPE"] = m.ItemName;
                }
                drTarget["GROUP_ID"] = drSelectedSource["GROUP_ID"];
                MstWorkingGroupEntity mWorkingGroup = MstWorkingGroupBs.GetMstWorkingGroupByID(drSelectedSource["GROUP_ID"].ToString());
                if (mWorkingGroup != null)
                {
                    drTarget["GROUP_NAME"] = mWorkingGroup.GroupName;
                }
                drTarget["QTY"] = mSelectedProdPlanOrderItem.Qty;
                string sCondition = " and TECHNIC_ID='" + drSelectedSource["TECHNIC_ID"].ToString() + "' and VALIDITY_FLAG=1";
                sCondition += " and VALIDITY_DATE_FROM<='" + DateTime.Now.ToString("yyyy-MM-dd") + "'";
                sCondition += " and VALIDITY_DATE_TO>='" + DateTime.Now.ToString("yyyy-MM-dd") + "'";
                DataTable dtCost = ProdTechnicCostBs.GetDtAllByCondition(sCondition);
                if (dtCost.Rows.Count != 0)
                {
                    drTarget["COST"] = dtCost.Rows[0]["COST"];
                }

                sCondition = " and TECHNIC_ID='" + drSelectedSource["TECHNIC_ID"].ToString() + "' and VALIDITY_FLAG=1";
                sCondition += " and QTY_FROM<='" + mSelectedProdPlanOrderItem.Qty.ToString() + "'";
                sCondition += " and QTY_TO>='" + mSelectedProdPlanOrderItem.Qty.ToString() + "'";
                DataTable dtRatio = ProdTechnicRatioBs.GetDtAllByCondition(sCondition);
                if (dtRatio.Rows.Count != 0)
                {
                    drTarget["COEFFICIENT"] = dtRatio.Rows[0]["RATIO"];
                }
                dtTarget.Rows.Add(drTarget);
            }
        }
        private void btnDel_Click(object sender, EventArgs e)
        {
            int[] arrySelectedIndex = gridView1.GetSelectedRows();
            if (arrySelectedIndex.Length == 0)
            {
                MessageBox.Show("请选择工序！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            List<DataRow> list = new List<DataRow>();
            for (int i = 0; i < arrySelectedIndex.Length; i++)
            {
                DataRow dr = gridView1.GetDataRow(arrySelectedIndex[i]);
                list.Add(dr);
            }
            DataTable dt = (DataTable)gvTargetStations.DataSource;
            foreach (DataRow dr in list)
            {
                dt.Rows.Remove(dr);
            }
        }
        private void btnUpMove_Click(object sender, EventArgs e)
        {
            int[] arrySelectedIndex = gridView1.GetSelectedRows();
            if (arrySelectedIndex.Length == 0)
            {
                MessageBox.Show("请选择工序！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else if (arrySelectedIndex.Length > 1)
            {
                MessageBox.Show("请选择一条需要调整的工序！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (arrySelectedIndex[0] == 0)
                return;
            DataTable dt = (DataTable)gvTargetStations.DataSource;
            DataTable dtDetail = dt.DataSet.Tables[1].Copy();
            DataRow drTemp = dt.NewRow();
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                drTemp[i] = dt.Rows[arrySelectedIndex[0]][i];
            }
            dt.Rows.Remove(gridView1.GetDataRow(arrySelectedIndex[0]));
            dt.Rows.InsertAt(drTemp, arrySelectedIndex[0] - 1);
            DataRow[] arryDataRow = dtDetail.Select("PRODUCT_TECHNIC_ID='" + drTemp["PRODUCT_TECHNIC_ID"].ToString() + "'");
            if (arryDataRow.Length > 0)
            {
                for (int i = 0; i < arryDataRow.Length; i++)
                {
                    dt.DataSet.Tables[1].ImportRow(arryDataRow[i]);
                }
            }
            gridView1.FocusedRowHandle = arrySelectedIndex[0] - 1;
        }
        private void btnDownMove_Click(object sender, EventArgs e)
        {
            int[] arrySelectedIndex = gridView1.GetSelectedRows();
            if (arrySelectedIndex.Length == 0)
            {
                MessageBox.Show("请选择工序！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else if (arrySelectedIndex.Length > 1)
            {
                MessageBox.Show("请选择一条需要调整的工序！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DataTable dt = (DataTable)gvTargetStations.DataSource;
            if (arrySelectedIndex[0] == dt.Rows.Count - 1)
                return;
            DataTable dtDetail = dt.DataSet.Tables[1].Copy();
            DataRow drTemp = dt.NewRow();
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                drTemp[i] = dt.Rows[arrySelectedIndex[0]][i];
            }
            dt.Rows.Remove(gridView1.GetDataRow(arrySelectedIndex[0]));
            dt.Rows.InsertAt(drTemp, arrySelectedIndex[0] + 1);
            DataRow[] arryDataRow = dtDetail.Select("PRODUCT_TECHNIC_ID='" + drTemp["PRODUCT_TECHNIC_ID"].ToString() + "'");
            if (arryDataRow.Length > 0)
            {
                for (int i = 0; i < arryDataRow.Length; i++)
                {
                    dt.DataSet.Tables[1].ImportRow(arryDataRow[i]);
                }
            }
            gridView1.FocusedRowHandle = arrySelectedIndex[0] + 1;
        }

        private void tsNew_Click(object sender, EventArgs e)
        {
            if (drSelectedMain == null)
                return;
            DataTable dtDetail = Ds.Tables[1];
            DataRow drDetail = dtDetail.NewRow();
            drDetail["PRODUCT_TECHNIC_ITEM_ID"] = Guid.NewGuid().ToString();
            drDetail["PRODUCT_TECHNIC_ID"] = drSelectedMain["PRODUCT_TECHNIC_ID"];
            dtDetail.Rows.Add(drDetail);
            gridView1.ExpandMasterRow(nFocusedRowIndex);
        }
        private void tsDel_Click(object sender, EventArgs e)
        {
            DataTable dtMain = (DataTable)gvTargetStations.DataSource;
            DataTable dtDetail = dtMain.DataSet.Tables[1];
            int SelectedMainHandle = -1;
            SelectedMainHandle = gridView1.FocusedRowHandle;
            DevExpress.XtraGrid.Views.Grid.GridView aView = (DevExpress.XtraGrid.Views.Grid.GridView)gridView1.GetDetailView(this.gridView1.GetSelectedRows()[0], 0);
            if (aView.GetSelectedRows().Length > 0
                && aView.GetFocusedDataRow() != null)
            {
                //仅仅删除选中的不良明细
                if (bIsModify)
                {
                    listDeleteItemDetail.Add(aView.GetFocusedDataRow());
                }
                dtDetail.Rows.Remove(aView.GetFocusedDataRow());
            }
            else if (SelectedMainHandle >= 0)//删除物料以及其下所有明细
            {
                string sItemID = dtMain.Rows[SelectedMainHandle]["PRODUCT_TECHNIC_ID"].ToString();
                DataRow[] arryDr = dtDetail.Select("PRODUCT_TECHNIC_ID='" + sItemID + "'");
                if (arryDr.Length > 0)
                {
                    if (bIsModify)
                    {
                        listDeleteItemDetail.AddRange(arryDr);
                    }
                    foreach (DataRow dr in arryDr)
                    {
                        dtDetail.Rows.Remove(dr);
                    }
                }
                if (bIsModify)
                {
                    listDeleteItem.Add(dtMain.Rows[SelectedMainHandle]);
                }
                dtMain.Rows.RemoveAt(SelectedMainHandle);
            }
        }

        private int nFocusedRowIndex = -1;
        private DataRow drSelectedMain;
        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            nFocusedRowIndex = e.RowHandle;
            drSelectedMain = gridView1.GetDataRow(gridView1.GetSelectedRows()[0]);
            tsNew.Enabled = true;
            tsDel.Enabled = true;
        }

        private void gridView1_MasterRowExpanded(object sender, DevExpress.XtraGrid.Views.Grid.CustomMasterRowEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView aView = (DevExpress.XtraGrid.Views.Grid.GridView)gridView1.GetDetailView(e.RowHandle, 0);
            if (aView != null)
            {
                aView.BestFitColumns();
                aView.Name = "加工人信息";
                aView.Columns["GROUP_PERSON_NAME"].Caption = "加工人";
                aView.Columns["GROUP_PERSON_NAME"].OptionsColumn.ReadOnly = true;
                aView.Columns["QTY"].Caption = "数量";
                aView.Columns["PLAN_STARTTIME"].Caption = "计划开始时间";
                aView.Columns["PLAN_ENDTIME"].Caption = "计划完成时间";               
                aView.Columns["TIME_COEFFICIENT"].Caption = "难度系数";
                aView.Columns["WORKCENTER_NAME"].Caption = "工作中心";
                aView.Columns["WORKCENTER_CODE"].Caption = "工作中心代码";                
                aView.Columns["WORKING_TIME"].Caption = "工时";

                if (aView.Columns.ColumnByFieldName("PRODUCT_TECHNIC_ITEM_ID") != null)
                {
                    aView.Columns["PRODUCT_TECHNIC_ITEM_ID"].VisibleIndex = -1;
                }
                if (aView.Columns.ColumnByFieldName("PRODUCT_TECHNIC_ID") != null)
                {
                    aView.Columns["PRODUCT_TECHNIC_ID"].VisibleIndex = -1;
                }
                if (aView.Columns.ColumnByFieldName("GROUP_PERSON") != null)
                {
                    aView.Columns["GROUP_PERSON"].VisibleIndex = -1;
                }
                if (aView.Columns.ColumnByFieldName("WORKCENTER_CODE") != null)
                {
                    aView.Columns["WORKCENTER_CODE"].VisibleIndex = -1;
                }

                //列绑定ButtonEdit
                RepositoryItemButtonEdit btnWorkingPerson = new RepositoryItemButtonEdit();
                gvTargetStations.RepositoryItems.Add(btnWorkingPerson);
                aView.Columns["GROUP_PERSON_NAME"].ColumnEdit = btnWorkingPerson;
                btnWorkingPerson.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(btnWorkingPerson_ButtonClick);
                RepositoryItemButtonEdit btnWorkcenter = new RepositoryItemButtonEdit();
                gvTargetStations.RepositoryItems.Add(btnWorkcenter);
                aView.Columns["WORKCENTER_NAME"].ColumnEdit = btnWorkcenter;
                btnWorkcenter.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(btnWorkcenter_ButtonClick);
            }
        }

        void btnWorkcenter_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainWorkcentersQuery frm = new frmMaintainWorkcentersQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedWorkcenter != null)
            {
                DevExpress.XtraGrid.Views.Grid.GridView gv = (DevExpress.XtraGrid.Views.Grid.GridView)gridView1.GetDetailView(nFocusedRowIndex, 0);
                int nSelectedDetailHandle = gv.GetSelectedRows()[0];
                DataRow dr = gv.GetDataRow(nSelectedDetailHandle);
                dr["WORKCENTER_NAME"] = frm.SelectedWorkcenter.Name;
                dr["WORKCENTER_CODE"] = frm.SelectedWorkcenter.Code ;
            }
        }
        private void btnWorkingPerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainWorkingGroupQuery frm = new frmMaintainWorkingGroupQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedMstWorkingGroupPerson != null)
            {
                string GroupPersonID = frm.SelectedMstWorkingGroupPerson.PersonId;
                MstPersonEntity mMstPerson = MstPersonBs.GetMstPersonByID(GroupPersonID);
                ((DevExpress.XtraEditors.ButtonEdit)sender).EditValue = mMstPerson.NameCn;
                DevExpress.XtraGrid.Views.Grid.GridView gv = (DevExpress.XtraGrid.Views.Grid.GridView)gridView1.GetDetailView(nFocusedRowIndex, 0);
                int nSelectedDetailHandle = gv.GetSelectedRows()[0];
                DataRow dr = gv.GetDataRow(nSelectedDetailHandle);
                dr["GROUP_PERSON_NAME"] = mMstPerson.NameCn;
                dr["GROUP_PERSON"] = mMstPerson.PersonId;
            }
        }

        protected override void Click_Save()
        {
            //判断该工令单是否生产
            ProdProductTechnicEntity m = ProdProductTechnicBs.GetProductTechnicByPlanOrderItemID(mSelectedProdPlanOrderItem.PlanOrderItemId);
            if (m != null)
            {
                MessageBox.Show("该工令单已报工，无法修改工艺，请开重工单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DataTable dtMain = gvTargetStations.DataSource as DataTable;
            DataTable dtDetail = dtMain.DataSet.Tables[1];
            if (ProdProductTechnicBs.SaveManufactoryTechnic(mSelectedProdPlanOrderItem, dtMain, dtDetail))
            {
                MessageBox.Show("保存成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        #endregion
    }
}
